package team.pwy;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.Tuple;

import java.util.Set;

public class GameLeaderboard {

    private Jedis jedis;

    // 连接redis
    public GameLeaderboard() {
        jedis = new Jedis("118.178.105.195", 6379);
        jedis.auth("roots");
    }

    // 更新得分
    public void updateScore(String playerId, double score) {
        jedis.zincrby("movieScore", score, playerId);
    }

    // 获取排名
    public Long getPlayerRank(String playerId) {
        return jedis.zrevrank("movieScore", playerId);
    }

    // 获取到排名前几名以及得分。
    public Set<Tuple> getTopPlayers(int count) {
        return jedis.zrevrangeWithScores("movieScore", 0, count - 1);
    }

    public static void main(String[] args) {
        GameLeaderboard leaderboard = new GameLeaderboard();
        //更新得分
        leaderboard.updateScore("player123", 1500);
        leaderboard.updateScore("player456", 1800);
        leaderboard.updateScore("player789", 1600);
        leaderboard.updateScore("player123", 2500);

        //    获取到排名前几名以及得分。
        Set<Tuple> topPlayers = leaderboard.getTopPlayers(3);
        topPlayers.forEach(tuple -> System.out.println(tuple.getElement() + ": " + tuple.getScore()));
    }
}